package com.example.rdb.handle.etcd;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.rdb.conf.ConfigInfo;
import com.example.rdb.conf.etcd.ReadEtcdUtil;
import com.example.rdb.conf.etcd.WriteEtcdUtil;
import com.example.rdb.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.*;

/**
 * @author XYC
 * @描述: TODO
 * @date 21.5.2817:32
 */
@Component
@Slf4j
public class EtcdMoveOne {

    private static String copyUrl = "/apisix/madp/";
    private static String route = "/apisix/routes/";
    private static String upstream = "/apisix/upstreams/";
    private static String service = "/apisix/services/";
    private static String ssl = "/apisix/ssl/";
    private static String consumers = "/apisix/consumers/";

    public void etcdMove() throws Exception {
        System.out.println("------ETCD-START------");
        //将查询出来的应用Id和租户Id拼接在key上
        Map<String, String> etcdValueList = ReadEtcdUtil.getEtcdValueList(copyUrl + ConfigInfo.tenantRead + "/" + ConfigInfo.appRead + "/");
        log.info("etcdValueList:" + etcdValueList.size());
        //添加外层路由和上游数据
        addRouteAndUpstream(etcdValueList);
        //遍历所有的key-value,将复制的数据添加到新的应用下
        Set<Map.Entry<String, String>> entrySet = etcdValueList.entrySet();
        for (Map.Entry<String, String> e : entrySet) {
            String key = e.getKey();
            String value = e.getValue();
//			log.info("value = " + value);
            String[] split = key.split("/");
            String newKey = split[split.length - 2] + "/" + split[split.length - 1];
            log.info("newKey = " + newKey);
            if (key.contains(copyUrl)) {
                WriteEtcdUtil.putEtcdValueByKey(copyUrl + ConfigInfo.tenantWrite + "/" + ConfigInfo.appWrite + "/" + newKey.replace(" ", ""), value);
            }else{
                WriteEtcdUtil.putEtcdValueByKey( key,value);
            }

        }
        Map<String, String> newList = WriteEtcdUtil.getEtcdValueList(copyUrl + ConfigInfo.tenantWrite + "/" + ConfigInfo.appWrite + "/");

        if (newList.isEmpty()) {
            log.info("Madp-etcd数据拷贝重写失败!");
        } else {
            log.info("madp-etcd数据拷贝重写成功!");
        }
        System.out.println("------ETCD-END------");
    }

    public void etcdMoveByJson() throws Exception {
        System.out.println("------ETCD-START------");
        //将查询出来的应用Id和租户Id拼接在key上
        String jsonStr = JsonUtils.readJsonFile(new File("etcd.json"));
        JSONObject json = JSONUtil.parseObj(jsonStr);
        Map map = json;
        //遍历所有的key-value,将复制的数据添加到新的应用下
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        for (Map.Entry<String, String> e : entrySet) {

            String key = e.getKey();
            System.out.println("key="+key);
            String value = e.getValue();
//			log.info("value = " + value);
            if (key.contains(copyUrl)) {
                String[] split = key.split("/");
                String newKey = split[split.length - 2] + "/" + split[split.length - 1];
//                log.info("newKey = " + newKey);
                WriteEtcdUtil.putEtcdValueByKey(copyUrl + ConfigInfo.tenantWrite + "/" + ConfigInfo.appWrite + "/" + newKey.replace(" ", ""), value);
            } else {
                WriteEtcdUtil.putEtcdValueByKey(key,value);
            }

        }
        Map<String, String> newList = WriteEtcdUtil.getEtcdValueList(copyUrl + ConfigInfo.tenantWrite + "/" + ConfigInfo.appWrite + "/");
        if (newList.isEmpty()) {
            log.info("Madp-etcd数据拷贝重写失败!");
        } else {
            log.info("madp-etcd数据拷贝重写成功!");
        }
        System.out.println("------ETCD-END------");
    }

    public void createJson() throws Exception {
        System.out.println("------ETCD-CREATE-JSON-START------");
        log.info(ConfigInfo.tenantRead + "|" + ConfigInfo.appRead);
        Map<String, String> etcdValueList = ReadEtcdUtil.getEtcdValueList(copyUrl + ConfigInfo.tenantRead + "/" + ConfigInfo.appRead + "/");
        //添加外层路由和上游数据
        addRouteAndUpstream(etcdValueList);
        JSONObject jsonObject = JSONUtil.parseObj(etcdValueList);
        OutputStreamWriter out = null;
        try {
            out = new OutputStreamWriter(new FileOutputStream("etcd.json"), "utf-8");
            out.write(jsonObject.toString());
            out.flush();//清空缓冲区，强制输出数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.close();//关闭输出流
        }
//        log.info(etcdValueList.toString());
        System.out.println("------ETCD-CREATE-JSON-END------");
    }

    private void addRouteAndUpstream(Map<String, String> etcdValueList) {
        Set<String> keys = new HashSet<>(etcdValueList.keySet());
        for (String k : keys) {
            System.out.println("etcd-key"+ k);
            if (k.contains("/route/")) {
                try {
                    String key = route + k.substring(k.lastIndexOf("/")+1);
                    String value = ReadEtcdUtil.getEtcdValueByKey(key);
                    etcdValueList.put(key, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (k.contains("/upstream/")) {
                try {
                    String key = upstream + k.substring(k.lastIndexOf("/")+1);
                    String value = ReadEtcdUtil.getEtcdValueByKey(key);
                    etcdValueList.put(key, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (k.contains("/service/")) {
                try {
                    String key = service + k.substring(k.lastIndexOf("/")+1);
                    String value = ReadEtcdUtil.getEtcdValueByKey(key);
                    etcdValueList.put(key, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (k.contains("/ssl/")) {
                try {
                    String key = ssl + k.substring(k.lastIndexOf("/")+1);
                    String value = ReadEtcdUtil.getEtcdValueByKey(key);
                    etcdValueList.put(key, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (k.contains("/consumers/")) {
                try {
                    String key = consumers + k.substring(k.lastIndexOf("/")+1);
                    String value = ReadEtcdUtil.getEtcdValueByKey(key);
                    etcdValueList.put(key, value);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void delete() throws Exception {
        System.out.println("------ETCD-DELETE-START------");
        WriteEtcdUtil.deleteEtcdValueListByKey(copyUrl + ConfigInfo.tenantWrite + "/" + ConfigInfo.appWrite + "/");
        System.out.println("------ETCD-DELETE-END------");
    }

}
